package org.hxzon.demo.netty;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;

public class FileDownloadClientHandler extends SimpleChannelHandler {
	long len = -1;
	long total = 0;
	OutputStream out = null;

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent event) {
		System.out.println("client");
		ChannelBuffer buf = (ChannelBuffer) event.getMessage();
		try {
			if (len == -1) {
				len = buf.readLong();
				out = new FileOutputStream(new File("d:/export/h.pcap"));
			}
//			byte[] data=new byte[buf.readableBytes()];
//			out.write(b);
			total += buf.readableBytes();
//			System.out.println("buf:"+buf+",out:"+out);
			buf.readBytes(out, buf.readableBytes());
			if (total == len) {
				out.close();
				event.getChannel().close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
//		event.getChannel().write((int) 1);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
		e.getCause().printStackTrace();
		e.getChannel().close();
	}
}